import express, { Request, Response } from 'express';
import cors from 'cors';
import { v4 as uuidv4 } from 'uuid';

// 定义待办事项的接口
interface Todo {
  id: string;
  text: string;
  completed: boolean;
  createdAt: Date;
}

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 5000;

// 中间件
app.use(cors());
app.use(express.json());

// 内存存储待办事项
let todos: Todo[] = [
  {
    id: uuidv4(),
    text: '学习TypeScript',
    completed: false,
    createdAt: new Date()
  },
  {
    id: uuidv4(),
    text: '构建Todo应用',
    completed: false,
    createdAt: new Date()
  }
];

// API路由

// 获取所有待办事项
app.get('/api/todos', (_req: Request, res: Response) => {
  res.json(todos);
});

// 添加新的待办事项
app.post('/api/todos', (req: Request, res: Response) => {
  const { text } = req.body;
  
  if (!text) {
    return res.status(400).json({ error: '待办事项内容不能为空' });
  }
  
  const newTodo: Todo = {
    id: uuidv4(),
    text,
    completed: false,
    createdAt: new Date()
  };
  
  todos.push(newTodo);
  res.status(201).json(newTodo);
});

// 更新待办事项状态
app.put('/api/todos/:id', (req: Request, res: Response) => {
  const { id } = req.params;
  const { completed } = req.body;
  
  const todoIndex = todos.findIndex(todo => todo.id === id);
  
  if (todoIndex === -1) {
    return res.status(404).json({ error: '待办事项不存在' });
  }
  
  todos[todoIndex] = {
    ...todos[todoIndex],
    completed: completed !== undefined ? completed : todos[todoIndex].completed
  };
  
  res.json(todos[todoIndex]);
});

// 删除待办事项
app.delete('/api/todos/:id', (req: Request, res: Response) => {
  const { id } = req.params;
  
  const todoIndex = todos.findIndex(todo => todo.id === id);
  
  if (todoIndex === -1) {
    return res.status(404).json({ error: '待办事项不存在' });
  }
  
  const deletedTodo = todos[todoIndex];
  todos = todos.filter(todo => todo.id !== id);
  
  res.json(deletedTodo);
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});